package com.xxxx.yoyo.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xxxx.yoyo.bean.Type;
import com.xxxx.yoyo.bean.User;
import com.xxxx.yoyo.service.ITypeService;
import com.xxxx.yoyo.service.IUserService;
import com.xxxx.yoyo.service.impl.TypeServiceImpl;
import com.xxxx.yoyo.service.impl.UserServiceImpl;

/**
 * Servlet implementation class RegjsterServlet
 */
@WebServlet("/index/register")
public class RegjsterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private ITypeService typeService = new TypeServiceImpl();
	private IUserService userService = new UserServiceImpl();
	
	// <a标签是超链接标签，只能用doGet请求， 此处刚好为点击注册图标进入
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置导航条上的[注册]处于选中状态
		request.setAttribute("flag",5);
		
		//获取[宠物分类]列表
		List<Type> typeList = typeService.getTypeList ();
		//把typeList存入request中，供/index/register.jsp使用
		request.setAttribute("typeList",typeList);
		
		
		//请求转发，跳转到/index/register.jsp
		request.getRequestDispatcher("/index/register.jsp").forward(request,response);

	}

	// 此处为用户已经在注册页面了。用户点击了注册按钮后触发的请求
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//设置编码格式为utf-8
		request.setCharacterEncoding("UTF-8");
		
		//获取前端提交的注册信息（前端提交的参数）
		String username = request.getParameter ("username");
		String password = request.getParameter ("password");
		String name = request.getParameter ("name");
		String phone = request.getParameter ("phone");
		String address = request.getParameter ("address");

		
		
		//注册之前，验证一下要注册的这个用户名是否已经存在.如果存在，不应该注册.如果不存在，可以注册
		
		//根据[用户名]查询用户信息
		User user = userService.getUserByUsername (username);
		if(user==null) {	//如果没有查询，说明这个用户名可以注册
			//根据注册信息，创建一个Use上对象
			User newUser = new User(null, username, password, name, phone, address, 1);
			//把新用户添加到数据库中
			boolean isSuccess = userService.addUser(newUser);
			if(isSuccess == true) {//添加成功
				//设置成功的提示信息
				request.setAttribute("msg","恭喜你注册成功！请前往登录页进行登录！");
			}else {//添加失败
				//设置错误的提示信息
				request.setAttribute("msg","注册信息有误，请检查后重新注册");
			}
		}else {		//用户名已经存在，应该给别人提示一个错误信息，并且还调回到注册页面
			//设置错误提示
			request.setAttribute("msg","用户名己经存在，请换个用户名注册！");
		}
		//设置导航条上的[注册]处于选中状态
		request.setAttribute("flag",5);
		
		//获取[宠物分类]列表
		List<Type> typeList = typeService.getTypeList ();
		//把typeList存入request中，供/index/register.jsp使用
		request.setAttribute("typeList",typeList);
		
		//请求转发，跳转到注册页面
		request.getRequestDispatcher("/index/register.jsp").forward(request,response);
	
	}

}
